package cn.com.woxitech.dev.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.UserService;

@RestController
@RequestMapping("/wjt")
public class RoomController {
	
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;
	

	@RequestMapping(value="/app/my_like_rooms",method=RequestMethod.POST)
	public Object my_like_rooms(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			
			jsonNode = JSONUtils.toJson(body);

			String unionid =jsonNode.get("unionid").asText();
			
			String refreshtype = "all";
			if( jsonNode.get("refreshtype") != null){
				//all, head, footer
				refreshtype = jsonNode.get("refreshtype").asText();
			}
			
			String orderby = "new";
			if(jsonNode.get("orderby") != null){
				orderby = jsonNode.get("orderby").asText();
			}
			if(orderby.equals("new")){
				orderby = "createtime";
			}else if(orderby.equals("hot")){
				orderby = "attendeeCount";
			}else if(orderby.equals("live")){
				orderby = "time";
			}else{
				orderby = "createtime";
			}
			
			long timestamp = System.currentTimeMillis();
			if(jsonNode.get("timestamp") != null){
				timestamp = Long.parseLong(jsonNode.get("timestamp").asText());
			}
			
			int pos = 0;
			if(jsonNode.get("pos") != null){
				pos = Integer.parseInt(jsonNode.get("pos").asText());
			}
			
			int size = 4;
			if(jsonNode.get("size") != null){
				size = Integer.parseInt(jsonNode.get("size").asText());
			}
			int newpos = pos;
			
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			List<String> roomUuidStrs = roomService.getMyLikedRoomUuidsByUserUuid(user.getUuid());

			List<WmRoom> rooms = new ArrayList<WmRoom>();
			
			if(roomUuidStrs.size() != 0){
				
				if(refreshtype.equals("all")){
					
					rooms = roomService.getRoomsByUuidList(roomUuidStrs, orderby);
					
				}else if(refreshtype.equals("head")){

					newpos = pos = 0;
					rooms = roomService.getHeadRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp, true);
					
				}else if(refreshtype.equals("footer")){
					
					rooms = roomService.getFooterRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp ,true);
				}
				
			}
			newpos = newpos + rooms.size();
			
			mp.put("pos", newpos);
			mp.put("rooms", rooms);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/app/my_rooms",method=RequestMethod.POST)
	public Object app_my_rooms(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			jsonNode = JSONUtils.toJson(body);

			String unionid =jsonNode.get("unionid").asText();
			
			String refreshtype = "all";
			if( jsonNode.get("refreshtype") != null){
				//all, head, footer
				refreshtype = jsonNode.get("refreshtype").asText();
			}
			
			String orderby = "new";
			if(jsonNode.get("orderby") != null){
				orderby = jsonNode.get("orderby").asText();
			}
			if(orderby.equals("new")){
				orderby = "createtime";
			}else if(orderby.equals("hot")){
				orderby = "attendeeCount";
			}else if(orderby.equals("live")){
				orderby = "time";
			}else{
				orderby = "createtime";
			}
			
			long timestamp = System.currentTimeMillis();
			if(jsonNode.get("timestamp") != null){
				timestamp = Long.parseLong(jsonNode.get("timestamp").asText());
			}
			
			int pos = 0;
			if(jsonNode.get("pos") != null){
				pos = Integer.parseInt(jsonNode.get("pos").asText());
			}
			
			int size = 4;
			if(jsonNode.get("size") != null){
				size = Integer.parseInt(jsonNode.get("size").asText());
			}
			int newpos = pos;
			

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			List<String> roomUuidStrs = roomService.getRoomUuidsByUuidAndOrgUuid(user.getUuid(),orgUuid);

			List<WmRoom> rooms = new ArrayList<WmRoom>();
			
			if(roomUuidStrs.size() != 0){
				
				if(refreshtype.equals("all")){
					
					rooms = roomService.getRoomsByUuidList(roomUuidStrs, orderby);
					
				}else if(refreshtype.equals("head")){
					
					newpos = pos = 0;
					rooms = roomService.getHeadRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp, true);
					
				}else if(refreshtype.equals("footer")){
					
					rooms = roomService.getFooterRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp, true);
				}
				
			}
			newpos = newpos + rooms.size();
			
			mp.put("pos", newpos);
			mp.put("rooms", rooms);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value="/app/user_details",method=RequestMethod.POST)
	public Object app_UserDetails(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String,Object> mp = new HashMap<String,Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String fromunionid = jsonNode.get("fromunionid").asText();
			String tounionid = jsonNode.get("tounionid").asText();
			

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			List<String> orgUuidList = appService.getOrguuidStrList();
			
			WmUser from = this.userService.getUserByUnionId(fromunionid);
			WmUser to = this.userService.getUserByUnionId(tounionid);
			
			
			List<WmRoom> rooms = new ArrayList<WmRoom>();
			
			if(appid == 1){
				rooms = roomService.getPublicRoomsByUserUuidAndOrgUuidStrList(to.getUuid(), orgUuidList ,"createtime");
			}else{
				rooms = roomService.getPublicRoomsByUserUuidAndOrgUuid(to.getUuid(), orgUuid ,"createtime");
			}
			
			mp.put("rooms", rooms);
			
			mp.put("unionid", tounionid);
			mp.put("headimgurl", to.getWxHeadimgurl());
			mp.put("name", to.getName());
			mp.put("followingcount", userService.getFollowingCount(to.getUuid()));
			mp.put("followercount", userService.getFollowerCount(to.getUuid()));
			
			mp.put("doesfollow", this.userService.doesUserFollowUser(from.getUuid(), to.getUuid()));
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/app/room_details",method=RequestMethod.POST)
	public Object app_RoomDetails(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String,Object> mp = new HashMap<String,Object>();
		
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String unionid = jsonNode.get("unionid").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			if (room == null) {
				return APIResultFactory.fail();
			}

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			if(user == null){
				user = this.userService.getUserByUuid(unionid);
			}
			WmUser create_user = this.userService.getUserByUuid(room.getCreatoruuid());
			
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			String ratio = lecture.getRatio();
			List<WmLecturePage> lecturePages = lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
			
			List<String> cataloguuids = new ArrayList<String>();
			List<String> cataloguuidStrList = catalogService.getCatalogUuidStrListByRoomUuid(roomuuid);
			for(String uuid : cataloguuidStrList){
				
				if(!uuid.equals(default_catalogUuid)){
					cataloguuids.add(uuid);
				}
			}
			
			mp.put("cover", room.getLivecoverurl());
			mp.put("status", room.getType());
			mp.put("name", room.getName());
			mp.put("attendcount", room.getAttendeecount().intValue());
			mp.put("maxconcurrent", room.getMaxconcurrent().intValue());
			mp.put("likecount", room.getLikecount().intValue());
			mp.put("uuid", room.getUuid());
			mp.put("livetype", room.getLiveType());
			mp.put("des", room.getDes());
			mp.put("starttime", room.getTime().getTime());
			mp.put("createtime", room.getCreatetime().getTime());
			
			mp.put("username", create_user.getName());
			mp.put("userunionid", create_user.getWxUnionid());
			mp.put("useruuid", create_user.getUuid());
			mp.put("userheadimgurl", create_user.getWxHeadimgurl());
			
			mp.put("pages", lecturePages);
			
			mp.put("doesfollow", this.userService.doesUserFollowUser(user.getUuid(), create_user.getUuid()));
			mp.put("doeslike", this.roomService.doesUserLikeroom(user.getUuid(), roomuuid));
			
			mp.put("roomtype", room.getRoomType());
			mp.put("chairs", room.getRoomchairs());
			
			mp.put("cataloguuids", cataloguuids);
			
			mp.put("chairlist", this.roomService.getRoomChairs(roomuuid));
			
			mp.put("pwd", room.getPwd());
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/app/room_status",method=RequestMethod.POST)
	public Object app_room_status(@RequestBody String body) {
		JsonNode jsonNode;
		
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String status =jsonNode.get("status").asText();
			String playurl =jsonNode.get("playurl").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			
			if(status.equals("3")){
				room.setType("3");
				roomService.updateByPrimaryKey(room);
			}
			
			WmLecture lecture = lectureService.getLectureByRoomUuid(room.getUuid());

			WmLecturePage lecturePage = lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
			
			if(lecturePage.getType().equals("live")){
				lecturePage.setType("video");
				lecturePage.setPageurl(playurl);
			}
			lecturePageService.updateByPrimaryKey(lecturePage);
			
			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/app/room_ppt_create",method=RequestMethod.POST)
	public Object app_room_ppt_create(@RequestBody String body){
		
		Map<String, Object> mp = new HashMap<String, Object>();
//		unionid: unionid,
//		title: title,
//		cover: cover,
//		des: des,
//		starttime: starttime,
//		roomtype: roomtype
		String publishurl ="";
		String publishid = "";
		String playurl = "";
		
		
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String systemType = jsonNode.get("systemType").asText();
			String unionid = jsonNode.get("unionid").asText();
			
			String cover = jsonNode.get("cover").asText();
			
			
			String des = "";
			if(systemType.equals("ios")){
				des = new String(jsonNode.get("des").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				des = jsonNode.get("des").asText();
			}
			
			String title = "";
			if(systemType.equals("ios")){
				title = new String(jsonNode.get("title").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				title = jsonNode.get("title").asText();
			}
					
					
			String _roomtype = jsonNode.get("roomtype").asText();
			String roomtyp = "1";
			long starttime = Long.parseLong(jsonNode.get("starttime").asText());
			
			WmUser user = userService.getUserByUnionId(unionid);
			String useruuid = user.getUuid();
			
			if(_roomtype.equals("公开")){
				roomtyp = "1";
			}else if(_roomtype.equals("密码")){
				roomtyp = "2";
				
			}else if(_roomtype.equals("收费")){
				roomtyp = "3";
				
			}else if(_roomtype.equals("授权")){
				roomtyp = "4";
				
			}
			

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			
			//设置room
			WmRoom room = new WmRoom();
			room.setCreatoruuid(useruuid);
			room.setOrguuid(orgUuid);
			room.setName(title);
			room.setDes(des);
			room.setRoomType(roomtyp);//1-公开
			room.setTime(new Date(starttime));
			room.setUuid(UUID.randomUUID().toString());
			room.setCreatetime(new Timestamp(System.currentTimeMillis()));
			room.setType("1");
			room.setCoverurl(cover);
			room.setLivecoverurl(cover);
			room.setRoomchairs(user.getName());
			room.setThumburl(user.getWxHeadimgurl());
			roomService.insertRoom(room);

			//设置room_chair
			//必须通过微信端进行设置
			
			//设置lecture
			WmLecture lecture = new WmLecture();
			lecture.setRoomid(room.getUuid());
			lecture.setName(room.getName());
			lecture.setRatio("0.5625");
			lecture.setUuid(UUID.randomUUID().toString());
			lecture.setCreatorid(useruuid);
			lecture.setTime(new Timestamp(System.currentTimeMillis()));
			lectureService.insertLecture(lecture);
			
			
			//设置catalog_room
			catalogService.insertCatalog_Room(default_catalogUuid, room.getUuid());
			
			
			mp.put("roomuuid", room.getUuid());
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
	
	
	@RequestMapping(value="/app/room_create",method=RequestMethod.POST)
	public Object app_createRoom(@RequestBody String body){
		
		Map<String, Object> mp = new HashMap<String, Object>();
//		unionid: unionid,
//		title: title,
//		cover: cover,
//		des: des,
//		starttime: starttime,
//		roomtype: roomtype
		String publishurl ="";
		String publishid = "";
		String playurl = "";
		
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String systemType = jsonNode.get("systemType").asText();
			String unionid = jsonNode.get("unionid").asText();
			
			String des = "";
			if(systemType.equals("ios")){
				des = new String(jsonNode.get("des").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				des = jsonNode.get("des").asText();
			}
			
			String title = "";
			if(systemType.equals("ios")){
				title = new String(jsonNode.get("title").asText().getBytes("ISO-8859-1"),"utf-8");
			}else{
				title = jsonNode.get("title").asText();
			}
			
			String livecover = null;
			if(jsonNode.get("livecover") != null){
				livecover = jsonNode.get("livecover").asText();
			}
			
			String cataloguuid = null;
			if(jsonNode.get("cataloguuid") !=null){
				cataloguuid = jsonNode.get("cataloguuid").asText();
			}
			
			
			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			
			
//			String _roomtype = jsonNode.get("roomtype").asText();
			String roomtype = "0";
			if(jsonNode.get("publictype") != null){
				roomtype = jsonNode.get("publictype").asText();
			}
			
			long starttime = System.currentTimeMillis();
			if(jsonNode.get("starttime") != null){
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
				Date time = formatter.parse(jsonNode.get("starttime").asText()); 
				starttime = time.getTime();
				
			}
			
			WmUser user = userService.getUserByUnionId(unionid);
			
			String chairs = user.getName();

			if(jsonNode.get("chairs") !=null){
				
				if(systemType.equals("ios")){
					chairs = new String(jsonNode.get("chairs").asText().getBytes("ISO-8859-1"),"utf-8");
				}else{
					chairs = jsonNode.get("chairs").asText();
				}
				
			}
			
			String roomuuid = UUID.randomUUID().toString();
			
			Map<String, Object> stream_map = qiniuService.createQiniuStream();
			publishurl = (String)stream_map.get("publishurl");
			publishid = (String)stream_map.get("streamid");
			playurl = (String)stream_map.get("playurl");
			
			
			String useruuid = user.getUuid();
			
			//设置room
			WmRoom room = new WmRoom();
			room.setCreatoruuid(useruuid);
			room.setOrguuid(orgUuid);
			room.setName(title);
			room.setDes(des);
			room.setRoomType(roomtype);//0-私有 1-公开
			room.setTime(new Date(starttime));
			room.setUuid(roomuuid);
			room.setCreatetime(new Timestamp(System.currentTimeMillis()));
			room.setType("1");
			
			if(livecover != null){
				room.setCoverurl(livecover);
				room.setLivecoverurl(livecover);
			}
			
			room.setRoomchairs(chairs);
			room.setThumburl(user.getWxHeadimgurl());
			roomService.insertRoom(room);
			
			//设置lecture
			WmLecture lecture = new WmLecture();
			lecture.setRoomid(room.getUuid());
			lecture.setName(room.getName());
			lecture.setRatio("0.5625");
			lecture.setUuid(UUID.randomUUID().toString());
			lecture.setCreatorid(useruuid);
			lecture.setTime(new Timestamp(System.currentTimeMillis()));
			lectureService.insertLecture(lecture);
			
			//设置lecturePage
			WmLecturePage lecturePage = new WmLecturePage();
			if(livecover != null){
				lecturePage.setThumburl(livecover);
			}
			
			lecturePage.setLectureid(lecture.getUuid());
			lecturePage.setNum(1);
			lecturePage.setType("live");
			lecturePage.setPageurl(playurl);
			lecturePage.setPublishurl(publishurl);
			lecturePage.setPublishid(publishid);
			lecturePageService.insertLecturePage(lecturePage);
			
			//设置catalog_room
			if(roomtype.equals("1")){
				catalogService.insertCatalog_Room(default_catalogUuid, room.getUuid());
				if(cataloguuid != null){
					catalogService.insertCatalog_Room(cataloguuid, room.getUuid());
				}
			}
			
			mp.put("roomuuid", room.getUuid());
			mp.put("publishurl", publishurl);
			mp.put("publishid", publishid);
			mp.put("roomInfo", room);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
	
	@RequestMapping(value="/app/room_update",method=RequestMethod.POST)
	public Object app_updateRoom(@RequestBody String body){
		
		Map<String, Object> mp = new HashMap<String, Object>();
		
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String systemType = jsonNode.get("systemType").asText();
			String unionid = jsonNode.get("unionid").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			
			
			String title = null;
			String des = null;
			String livecover = null;
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			
			if(jsonNode.has("title")){
				if(systemType.equals("ios")){
					title = new String(jsonNode.get("title").asText().getBytes("ISO-8859-1"),"utf-8");
				}else{
					title = jsonNode.get("title").asText();
				}
				
				room.setName(title);
				
			}
			if(jsonNode.has("des")){
				if(systemType.equals("ios")){
					des = new String(jsonNode.get("des").asText().getBytes("ISO-8859-1"),"utf-8");
				}else{
					des = jsonNode.get("des").asText();
				}
				room.setDes(des);
			}
			if(jsonNode.has("livecover")){
				livecover = jsonNode.get("livecover").asText();
				
				if(livecover == null || livecover.equals("") || livecover.equals("null")){
					livecover = null;
				}
				
				room.setCoverurl(livecover);
				room.setLivecoverurl(livecover);
				
				WmLecture lecture = this.lectureService.getLectureByRoomUuid(room.getUuid());
				WmLecturePage lecturePage = this.lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
				lecturePage.setThumburl(livecover);		
				
				this.lecturePageService.updateByPrimaryKeyHard(lecturePage);

			}
			if(jsonNode.has("starttime")){
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
				Date time = formatter.parse(jsonNode.get("starttime").asText()); 
				room.setTime(time);
			}
			
			
			WmUser user = userService.getUserByUnionId(unionid);
			
			String chairs = user.getName();

			if(jsonNode.get("chairs") !=null){
				
				if(systemType.equals("ios")){
					chairs = new String(jsonNode.get("chairs").asText().getBytes("ISO-8859-1"),"utf-8");
				}else{
					chairs = jsonNode.get("chairs").asText();
				}
				room.setRoomchairs(chairs);
			}
			
			if(jsonNode.has("starttime")){
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
				Date time = formatter.parse(jsonNode.get("starttime").asText()); 
				room.setTime(time);
			}
			
			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			if(jsonNode.has("roomtype")){
				room.setRoomType(jsonNode.get("roomtype").asText());
			}
			
			
			if(room.getRoomType().equals("0")){
				
				this.catalogService.deleteByRoomUuid(room.getUuid());
				
			}else if(room.getRoomType().equals("1")){

				boolean hasDefaultCatalog = false;
				
				if(jsonNode.has("cataloguuid")){
					
					String cataloguuid = jsonNode.get("cataloguuid").asText();
					List<String> l = this.catalogService.getCatalogUuidStrListByRoomUuid(roomuuid);
					for(String c_uuid: l){
						if(c_uuid.equals(default_catalogUuid)){
							hasDefaultCatalog = true;
						}else{
							this.catalogService.deleteByCatalogUUidAndRoomUuid(c_uuid,roomuuid);
						}
					}
					if((!cataloguuid.equals("")) && (!cataloguuid.equals("0"))){
						this.catalogService.insertCatalog_Room(cataloguuid, roomuuid);
					}
					
					
				}else{
					
					List<String> l = this.catalogService.getCatalogUuidStrListByRoomUuid(roomuuid);
					for(String c_uuid: l){
						if(c_uuid.equals(default_catalogUuid)){
							hasDefaultCatalog = true;
						}else{
							this.catalogService.deleteByCatalogUUidAndRoomUuid(c_uuid,roomuuid);
						}
					}
				}

				if(!hasDefaultCatalog){
					this.catalogService.insertCatalog_Room(default_catalogUuid, roomuuid);
				}
			}
			this.roomService.updateByPrimaryKeyHard(room);
			
			return APIResultFactory.success();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}	

	@RequestMapping(value="/app/room_delete",method=RequestMethod.POST)
	public Object app_room_delete(@RequestBody String body){
		
		Map<String, Object> mp = new HashMap<String, Object>();
		
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String useruuid = jsonNode.get("useruuid").asText();
			String roomuuid = jsonNode.get("roomuuid").asText();
			
			WmUser user = new WmUser();
			user = this.userService.getUserByUuid(useruuid);
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			
			if(room.getCreatoruuid().equals(user.getUuid())){
				//该用户有权限删除
				
				WmLecture lecture = this.lectureService.getLectureByRoomUuid(room.getUuid());
				
				this.lecturePageService.deleteByLectureUuid(lecture.getUuid());
				this.lectureService.deleteByRoomUuid(room.getUuid());
				this.roomService.deleteByPrimarykey(room);
				this.catalogService.deleteByRoomUuid(room.getUuid());
				
				return APIResultFactory.success();
			}else{
				
				return APIResultFactory.fail();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}


	@RequestMapping(value = "/app/save_snapshot",method=RequestMethod.POST)
	public Object app_save_snapshot(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String roomuuid = jsonNode.get("roomuuid").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lecturePage = lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
			String streamid = lecturePage.getPublishid();
			
			String snapshoturl = qiniuService.getSnapshotImg(streamid);
			//snapshoturl 也可以等于null
			
			room.setCoverurl(snapshoturl);
			room.setLivecoverurl(snapshoturl);
			roomService.updateByPrimaryKey(room);
			
			lecturePage.setThumburl(snapshoturl);
			lecturePageService.updateByPrimaryKey(lecturePage);
			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}
	
	@RequestMapping(value = "/app/close_publish",method=RequestMethod.POST)
	public Object app_close_publish(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String roomuuid = jsonNode.get("roomuuid").asText();
			
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lecturePage = null;
			
			String streamid = "";
			if(room.getLiveType().equals("1")){//视频直播，取一个页面
				lecturePage = lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
				streamid = lecturePage.getPublishid();
			}else if(room.getLiveType().equals("2")){//ppt直播，取smalllive类型的页面
				List<WmLecturePage> pages = lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
				for(int i =0 ;i < pages.size(); i++){
					if(pages.get(i).getType().equals("smalllive")){
						streamid = pages.get(i).getPublishid();
						lecturePage = pages.get(i);
					}
				}
			}
			
			String playurl = qiniuService.savePlaybackRecord(streamid);
			
			room.setType("3");
			roomService.updateByPrimaryKey(room);
			
			if(playurl !=null){
				lecturePage.setPageurl(playurl);
				lecturePageService.updateByPrimaryKey(lecturePage);				
			}

			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}
	@RequestMapping(value = "/app/continue_publish",method=RequestMethod.POST)
	public Object app_continue_publish(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String roomuuid = jsonNode.get("roomuuid").asText();
			
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lecturePage = lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
			String streamid = lecturePage.getPublishid();
			
			int status = qiniuService.getStreamStatus(streamid);
			/*
			 * 0 - disconnected
			 * 1 - connected
			 * 2 - Not Found
			 * 3 - Segments is null
			 * 4 - 其他
			 * */
			
			if(status == 0 || status == 3){
				room.setType("1");
				roomService.updateByPrimaryKey(room);
				
				Map<String, String> m1 = qiniuService.getStreamUrlsByStreamId(streamid);
						
				lecturePage.setPageurl(m1.get("playurl"));
				lecturePageService.updateByPrimaryKey(lecturePage);
			}
			
			return APIResultFactory.success(""+status);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}	
			
	@RequestMapping(value = "/app/stream_status",method=RequestMethod.POST)
	public Object app_stream_status(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String roomuuid = jsonNode.get("roomuuid").asText();
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lecturePage = lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
			String streamid = lecturePage.getPublishid();
			
			int status = qiniuService.getStreamStatus(streamid);
			/*
			 * 0 - disconnected
			 * 1 - connected
			 * 2 - Not Found
			 * 3 - Segments is null
			 * 4 - 其他
			 * */
			
			if(status == 0 || status == 1){
				return APIResultFactory.success();
			}else{
				return APIResultFactory.fail();				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}	
	
	@RequestMapping(value = "/app/unfollow_unionid",method=RequestMethod.POST)
	public Object app_unfollow_unionid(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String fromunionid = jsonNode.get("fromunionid").asText();
			String tounionid = jsonNode.get("tounionid").asText();
			
			if(fromunionid.equals(tounionid)){
				return APIResultFactory.fail();
			}
			
			WmUser fromUser = this.userService.getUserByUnionId(fromunionid);
			WmUser toUser = this.userService.getUserByUnionId(tounionid);
			
			this.userService.removeFollowUser(fromUser.getUuid(), toUser.getUuid());
			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}	
	
	@RequestMapping(value = "/app/follow_unionid",method=RequestMethod.POST)
	public Object app_follow_unionid(@RequestBody String body){
		
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String fromunionid = jsonNode.get("fromunionid").asText();
			String tounionid = jsonNode.get("tounionid").asText();
			
			if(fromunionid.equals(tounionid)){
				return APIResultFactory.fail();
			}
			
			WmUser fromUser = this.userService.getUserByUnionId(fromunionid);
			WmUser toUser = this.userService.getUserByUnionId(tounionid);
			
			this.userService.addFollowUser(fromUser.getUuid(), toUser.getUuid());
			
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}	
	
	@RequestMapping(value = "/app/my_followinfo",method=RequestMethod.POST)
	public Object app_my_followinfo(@RequestBody String body){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String unionid = jsonNode.get("unionid").asText();

			int appid = 1;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 1;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			
			mp.put("followingCount", this.userService.getFollowingCount(user.getUuid()));
			mp.put("followerCount", this.userService.getFollowerCount(user.getUuid()));
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("my_followinfo....fail...");
			return APIResultFactory.fail();
		}
		
		
		
	}	
	
	@RequestMapping(value = "/app/following_user",method=RequestMethod.POST)
	public Object app_following_user(@RequestBody String body){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String unionid = jsonNode.get("unionid").asText();
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			
			List<WmUser> users = this.userService.getFollowingUsersByUuid(user.getUuid());
			
			ArrayNode an = JSONUtils.arrayInit();
			
			for(WmUser u : users){
				
				SimpleDateFormat sf = new  SimpleDateFormat("yyyy-MM-dd HH:mm a");
				
				ObjectNode t = JSONUtils.jsonInit();
				t.put("name", u.getName());
				t.put("headimgurl", u.getWxHeadimgurl());
				t.put("unionid", u.getWxUnionid());
				t.put("lastlogin",sf.format(u.getLastlogin()));
				t.put("useruuid", u.getUuid());
				an.add(t);
			}
			mp.put("users", an);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}	
	@RequestMapping(value = "/app/follower_user",method=RequestMethod.POST)
	public Object app_follower_user(@RequestBody String body){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String unionid = jsonNode.get("unionid").asText();
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			
			List<WmUser> users = this.userService.getFollowerUsersByUuid(user.getUuid());
			
			ArrayNode an = JSONUtils.arrayInit();
			
			for(WmUser u : users){
				
				SimpleDateFormat sf = new  SimpleDateFormat("yyyy-MM-dd HH:mm a");
				
				ObjectNode t = JSONUtils.jsonInit();
				t.put("name", u.getName());
				t.put("headimgurl", u.getWxHeadimgurl());
				t.put("unionid", u.getWxUnionid());
				t.put("lastlogin",sf.format(u.getLastlogin()));
				t.put("useruuid", u.getUuid());
				an.add(t);
			}
			mp.put("users", an);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}		
	@RequestMapping(value = "/app/app_upload_tube",method=RequestMethod.POST)
	public Object app_upload_tube(@RequestBody String body){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			
			String roomuuid = jsonNode.get("roomuuid").asText();
			String pageurl = jsonNode.get("pageurl").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setType("3");
			room.setLiveType("3");
			WmLecture lecture = this.lectureService.getLectureByRoomUuid(roomuuid);
			WmLecturePage lecturePage = this.lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
			lecturePage.setPageurl(pageurl);
			lecturePage.setType("tube");
			
			this.roomService.updateByPrimaryKeyHard(room);
			this.lecturePageService.updateByPrimaryKeyHard(lecturePage);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}		
	
	
	
	@RequestMapping(value="/room_create",method=RequestMethod.POST)
	public Object createRoom(@RequestBody String body){
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").asText();
			String orguuid = jsonNode.get("orguuid").asText();
			String name = jsonNode.get("name").asText();
			String roomtype = jsonNode.get("roomtype").asText();
			String time = jsonNode.get("time").asText();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			WmUser user = userService.getUserByUnionId(unionid);
			String useruuid = user.getUuid();
			WmRoom room = new WmRoom();
			room.setCreatoruuid(useruuid);
			room.setOrguuid(orguuid);
			room.setName(name);
			room.setRoomType(roomtype);
			room.setTime(dateFormat.parse(time));
			room.setUuid(UUID.randomUUID().toString());
			room.setCreatetime(new Timestamp(System.currentTimeMillis()));
			room.setType("1");
			
			if(roomtype.equals("2")){
				if (jsonNode.has("password")) {
					String password = jsonNode.get("password").asText();
					room.setPwd(password);
				}				
			}
			if(roomtype.equals("3")){
				if (jsonNode.has("fee")) {
					double fee = jsonNode.get("fee").asDouble();
					room.setFee(fee);
				}				
			}

			roomService.insertRoom(room);
			
			WmLecture lecture = new WmLecture();
			lecture.setRoomid(room.getUuid());
			lecture.setName(room.getName());
			lecture.setRatio("0.5625");
			lecture.setUuid(UUID.randomUUID().toString());
			lecture.setCreatorid(useruuid);
			lecture.setTime(new Timestamp(System.currentTimeMillis()));
			lectureService.insertLecture(lecture);
			
			return APIResultFactory.success(room.getUuid());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		} 
		
	}
	
	@RequestMapping(value="/room_details",method=RequestMethod.POST)
	public Object getRoomDetails(@RequestBody String body) {
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			if (room == null) {
				return APIResultFactory.fail();
			}
			
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			String ratio = lecture.getRatio();
			List<WmLecturePage> lecturePages = lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
			
			
			RoomManager roomManager = new RoomManager();
			roomManager.setLivecoverurl(room.getLivecoverurl());
			roomManager.setStatus(room.getType());
			roomManager.setStarttime(room.getTime());
			roomManager.setDes(room.getDes());
			roomManager.setLecturePages(lecturePages);
			roomManager.setName(room.getName());
			roomManager.setRatio(ratio);
			roomManager.setThumburl(room.getThumburl());
			roomManager.setUuid(roomuuid);
			return APIResultFactory.success(roomManager);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	@RequestMapping(value="/room_update",method=RequestMethod.POST)
	public Object updateRoomDetails(@RequestBody String body) {
		JsonNode jsonNode;
		int id = -1;
		String roomuuid = null;
		String name = null;
		String des = null;
		String roomthumburl = null;
		String ratio = null;
		String pageurl = null;
		String thumburl = null;
		int num = -1;
		try {
			jsonNode = JSONUtils.toJson(body);
			if (jsonNode.has("id")) {
				id = jsonNode.get("id").asInt();
			}
			if (jsonNode.has("roomuuid")) {
				roomuuid = jsonNode.get("roomuuid").asText();
			}
			if (jsonNode.has("name")) {
				name = jsonNode.get("name").asText();
			}
			if (jsonNode.has("des")) {
				des = jsonNode.get("des").asText();
			}
			if (jsonNode.has("roomthumburl")) {
				roomthumburl = jsonNode.get("roomthumburl").asText();
			}
			if (jsonNode.has("ratio")) {
				ratio = jsonNode.get("ratio").asText();
			}
			if (jsonNode.has("pageurl")) {
				pageurl = jsonNode.get("pageurl").asText();
			}
			if (jsonNode.has("thumburl")) {
				thumburl = jsonNode.get("thumburl").asText();
			}
			if (jsonNode.has("num")) {
				num = jsonNode.get("num").asInt();
			}
			if (roomuuid != null) {
				WmRoom room = roomService.getRoomsByUuid(roomuuid);
				if (!StringUtils.isEmpty(name)) {
					room.setName(name);
				}
				if (!StringUtils.isEmpty(des)) {
					room.setDes(des);
				}
				if (!StringUtils.isEmpty(roomthumburl)) {
					room.setThumburl(roomthumburl);
				}
				if (!(name == null && des == null && roomthumburl == null)) {
					roomService.updateByPrimaryKey(room);
				}
				
				
				WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
				if (!StringUtils.isEmpty(ratio)) {
					lecture.setRatio(ratio);
					lectureService.updateByPrimaryKey(lecture);
				}
			}
			
			
			if (id > -1) {
				WmLecturePage lecturePage = lecturePageService.selectByPrimaryKey(id);
				if (!StringUtils.isEmpty(pageurl)) {
					lecturePage.setPageurl(pageurl);
				}
				if (!StringUtils.isEmpty(thumburl)) {
					lecturePage.setThumburl(thumburl);	
				}
				if (num > -1) {
					lecturePage.setNum(num);
				}
				lecturePageService.updateByPrimaryKey(lecturePage);
			}
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/lecture_page_create",method=RequestMethod.POST)
	public Object createLecturePage(@RequestBody String body) {
		JsonNode jsonNode;
		String thumburl = null;
		try {
			jsonNode = JSONUtils.toJson(body);
			if (jsonNode.has("thumburl")) {
				thumburl = jsonNode.get("thumburl").asText();
			}
			String roomuuid = jsonNode.get("roomuuid").asText();
			String pageurl = jsonNode.get("pageurl").asText();
			String type = jsonNode.get("type").asText();
			int num = jsonNode.get("num").asInt();
			String unionid = jsonNode.get("unionid").asText();
			WmUser user = userService.getUserByUnionId(unionid);
			String useruuid = user.getUuid();
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			String lectureUuid = lecture.getUuid();
			WmLecturePage lecturePage = new WmLecturePage();
			lecturePage.setLectureid(lectureUuid);
			lecturePage.setTime(new Timestamp(System.currentTimeMillis()));
			lecturePage.setNum(num);
			lecturePage.setPageurl(pageurl);
			lecturePage.setType(type);
			if (StringUtils.isEmpty(thumburl)) {
				lecturePage.setThumburl(thumburl);
			}
			lecturePage.setCreatorid(useruuid);
			lecturePageService.insertLecturePage(lecturePage);
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/ppt_page_count",method=RequestMethod.POST)
	public Object ppt_page_count(@RequestBody String body) {
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String key = jsonNode.get("key").textValue();
			
			String pid = QiniuPhotoUploadUtils.pagecountPfop(key, Const.Bucket_HAOJSQINIU);
			
			if(pid == null)
				return APIResultFactory.fail();
			else
				return APIResultFactory.success(pid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		return APIResultFactory.fail();
	}
	
	
	@RequestMapping(value="/flow_url_send",method=RequestMethod.POST)
	public Object sendFlowUrl(@RequestBody String body) {
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").asText();
			String url = jsonNode.get("url").asText();
			WmUser user = userService.getUserByUnionId(unionid);
			String tel = user.getTel();
			smsCodeService.sendUrl(tel, url);
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/room_status",method=RequestMethod.POST)
	public Object updateRoomStatus(@RequestBody String body) {
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String status = jsonNode.get("status").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			if (room == null) {
				return APIResultFactory.fail();
			}
			room.setType(status);
			roomService.updateByPrimaryKey(room);
			return APIResultFactory.success(roomuuid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/img_create",method=RequestMethod.POST)
	public Object createImgs(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			int page_total = jsonNode.get("page_total").asInt();
			String key = jsonNode.get("key").asText();
			String imgurlbase = Const.QINIU_BASE_URL;

			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			
			//清除原先的ppt_page
			lecturePageService.deleteByLectureUuid(lecture.getUuid());
			
			
			WmLecturePage lp = new WmLecturePage();
			String imgformatBase = "yifangyun_preview/v2/format=jpg/page_number=";
			Date time = new Date(System.currentTimeMillis());
			for(int i =0 ;i < page_total ; i++){
				String imgformat = imgformatBase + (i+1);
				String targetKey  = key+"_"+(i+1)+".jpg";
				
				QiniuUploadResult result = QiniuPhotoUploadUtils.upload(key, targetKey, imgurlbase,imgformat,Const.Bucket_HAOJSQINIU, Const.Bucket_HAOJSQINIU);
				
				String  savedUrl  = result.getResult();
				
				lp.setCreatorid(lecture.getCreatorid());
				lp.setNum(new Integer(i+1));
				lp.setLectureid(lecture.getUuid());
				lp.setPageurl(savedUrl);
				lp.setTime(time);
				lecturePageService.insertLecturePage(lp);
			}
			return APIResultFactory.success();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/img_num",method=RequestMethod.POST)
	public Object getImgNum(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			int page_init = jsonNode.get("page_init").asInt();
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			int now_total = lecturePageService.getPages(lecture.getUuid());
			return APIResultFactory.success(now_total-page_init);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/lecture_app_list",method=RequestMethod.POST)
	public Object lecture_app_list(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").textValue();
//			int start = jsonNode.get("start").intValue();
//			int len = jsonNode.get("len").intValue();
			
			List<String> users_l = new ArrayList<String>();
			List<String> orgs_l = new ArrayList<String>();
			orgs_l.add("efef8a1d-c5eb-4fe5-bbde-2a7a532636a1"); // hjs
			orgs_l.add("faab7a87-5afa-47e6-aadc-226c88543333"); // skd
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			users_l.add(user.getUuid());
			List<WmRoom> list_room = this.roomService.getRoomsByUserUuidStrListAndOrgUuidStrList(users_l, orgs_l);
			List<String> roomStrs = new ArrayList<String>();
			
			for(WmRoom room : list_room){
				roomStrs.add(room.getUuid());
			}
			
			List<WmLecture> lectures = this.lectureService.getLectureListByRooms(roomStrs);
			
			List<Lecture> list_lecture = new ArrayList<Lecture>();
			
			for(WmRoom room : list_room){
				
				Lecture l = new Lecture();
				l.setHeadimgurl(room.getThumburl());
				l.setName(room.getName());
				l.setStarttime(room.getTime().toLocaleString());
				l.setRoomUuid(room.getUuid());
				
				for(WmLecture lecture: lectures){
					if(room.getUuid().equals(lecture.getRoomid())){
						l.setPptulr(lecture.getPpturl());						
						l.setLectureUuid(lecture.getUuid());
						WmLecturePage firstPage = this.lecturePageService.getFirstLecturePageByLectureUuid(lecture.getUuid());
						if(firstPage != null){
							l.setFirstPageUrl(firstPage.getPageurl());
							l.setPageType(firstPage.getType());							
						}
						break;
					}
				}
				
				list_lecture.add(l);
				
			}
			
			
			
			return APIResultFactory.success(list_lecture);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/lecture_list",method=RequestMethod.POST)
	public Object lecture_list(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String unionid = jsonNode.get("unionid").textValue();
//			int start = jsonNode.get("start").intValue();
//			int len = jsonNode.get("len").intValue();
			
			WmUser user = this.userService.getUserByUnionId(unionid);
			List<WmRoom> list_room = this.roomService.getRoomsByUserUuid(user.getUuid());
			List<String> roomStrs = new ArrayList<String>();
			
			for(WmRoom room : list_room){
				roomStrs.add(room.getUuid());
			}
			
			List<WmLecture> lectures = this.lectureService.getLectureListByRooms(roomStrs);
			
			List<Lecture> list_lecture = new ArrayList<Lecture>();
			
			for(WmRoom room : list_room){
				
				Lecture l = new Lecture();
				l.setHeadimgurl(room.getThumburl());
				l.setName(room.getName());
				l.setStarttime(room.getTime().toLocaleString());
				l.setRoomUuid(room.getUuid());
				
				for(WmLecture lecture: lectures){
					if(room.getUuid().equals(lecture.getRoomid())){
						l.setPptulr(lecture.getPpturl());						
						l.setLectureUuid(lecture.getUuid());
						String firstPageUrl = this.lecturePageService.getFirstLecturePageUrlByLectureUuid(lecture.getUuid());
						l.setFirstPageUrl(firstPageUrl);
					}
				}
				
				list_lecture.add(l);
				
			}
			
			
			
			return APIResultFactory.success(list_lecture);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/crossdomain",method=RequestMethod.POST)
	public Object crossdomain(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String url = jsonNode.get("url").asText();
			String resp = HttpClientUtils.sendGET(url);
			
			return APIResultFactory.success(resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}

	
	@RequestMapping(value="/get_roomurl",method=RequestMethod.POST)
	public Object get_roomurl(@RequestBody String body){
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String unionind = jsonNode.get("unionid").asText();
			String appid = jsonNode.get("appid").asText();
			
			WmUser user = this.userService.getUserByUnionId(unionind);
			String useruuid = user.getUuid();
			
			String url = "http://www.haojs.com.cn/pages/wm/app/"+appid+"/room/"+roomuuid+"/user/"+useruuid;
			
			return APIResultFactory.success(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value="/init_online",method=RequestMethod.POST)
	public Object init_online(@RequestBody String body){
		
		try {
			ArrayNode an = JSONUtils.arrayInit();
			JsonNode jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
        	List<WmUser> users = this.roomService.getOnlineUser(roomuuid, 10);
        	
        	if(users != null){
	        	for(WmUser user : users){
	            	ObjectNode nc_temp = JSONUtils.jsonInit();
	            	nc_temp.put("headimgurl", user.getWxHeadimgurl());
	            	nc_temp.put("unionid", user.getWxUnionid());
	        		nc_temp.put("name", user.getName());
	        		an.add(nc_temp);
	        	}
        	}
        	
			return APIResultFactory.success(an);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	
	@RequestMapping(value = "/fetchhistory",method=RequestMethod.POST)
	public Object history(@RequestBody String body){
		int size = 50;
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomuuid").asText();
			String timestamp = jsonNode.get("timestamp").asText();
			if(jsonNode.has("size")){
				size = jsonNode.get("size").asInt();//默认是50	
			}
			
			List<WmChathistoryFetch> list = roomService.fetchHistory(roomuuid, timestamp, size);
			
			return APIResultFactory.success(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}
	
	
	
}
